package com.tarena.lbs.basic.web.filter;

import com.alibaba.nacos.api.utils.StringUtils;
import com.tarena.lbs.common.passport.encoder.JwtEncoder;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
@Slf4j
public class UserFilter implements Filter {
    @Autowired
    private JwtEncoder<UserPrinciple> jwtEncoder;
    /**
     *
     * @param servletRequest    请求对象
     * @param servletResponse   响应对象
     * @param filterChain       过滤链
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("你好,我是第一个过滤器 进入");
        //1、从请求获取请求头
        UserPrinciple userPrinciple = null;
        if (servletRequest instanceof HttpServletRequest){
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            //2、拿出头
            String jwt = request.getHeader("Authorization");
            if (!StringUtils.isEmpty(jwt)){
                try{
                   userPrinciple = jwtEncoder.getLoginFromToken(jwt,UserPrinciple.class);
                }catch (Exception e){
                    log.error("解析token失败",e);
                }
            }
        }
        //使用ThreadLocal传递参数

        UtilsThreadLocal.setValue(userPrinciple);

        filterChain.doFilter(servletRequest,servletResponse);
        log.info("你好,我是第一个过滤器 出去");

        UtilsThreadLocal.clear();
    }
}
